package game.module.mj.processor;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.hall.logic.QipaiConstants;
import game.module.hall.logic.QipaiDataManager;
import game.module.mj.bean.MjRoom;
import game.module.mj.logic.MjDataManager;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageMj.PushMJDismissRoom;
import lua.LuaMessageMj.PushMJForceDismissRoom;
import lua.LuaMessageMj.S2CMJDismissRoom;
import lua.LuaMessageMj.S2CMjForceDismisroom;
import lua.LuaMessageMj.C2SMjForceDismisroom;

@MsgCodeAnn(msgcode = C2SMjForceDismisroom.id, accessLimit = 500)
public class MjDismissRoomProcessor extends PlayingRoleMsgProcessor{

	private static Logger logger = LoggerFactory.getLogger(MjDismissRoomProcessor.class);
	@Override
	public void process(PlayingRole hero, RequestMessageRaw request) throws Exception {
		// TODO Auto-generated method stub
		int playerId = hero.getId();
		logger.info("Mj dismiss room,playeyId={}", playerId);
		//是否在房间中
		boolean isInRoom = MjDataManager.getInstance().isPlayerInRoom(playerId);
		if (!isInRoom) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// is room exist
		MjRoom mjRoom = MjDataManager.getInstance().getMjRoomByPlayerId(playerId);
		if (mjRoom == null) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
//		//is room master
//		if(mjRoom.getPlayerList().get(0)!=playerId){
//			S2ErrorCode respMsg = new S2ErrorCode(107);
//			hero.writeAndFlush(respMsg.build(hero.alloc()));
//			return;
//		}
		//push
		S2CMjForceDismisroom msg = new S2CMjForceDismisroom();
		hero.writeAndFlush(msg.build(hero.alloc()));
		
		List<Integer> playerIdList = mjRoom.getPlayerList();
		PushMJForceDismissRoom pushMsg = new PushMJForceDismissRoom();
		pushMsg.player_index = (byte) playerIdList.indexOf(playerId);
		for(Integer aPlayerId : playerIdList){
			PlayingRole pr =SessionManager.getInstance().getPlayer(aPlayerId);
			if(pr != null&&pr.isChannelActive()){
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
			}
		}
		//do
		MjDataManager.getInstance().removeRoom(mjRoom.getUuid());
		QipaiDataManager.getInstance().removeRoomUuid(mjRoom.getUuid());
		//send
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub
		
	}

}
